"""Anonycoin --- Bitcoin simulator with anonymity throught group signature

Copyright (c) 2016 Daniel Pimentel <d4n1@member.fsf.org>

This file is part Anonycoin.

Anonycoin is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or (at
your option) any later version.

Anonycoin is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Anonycoin.  If not, see <http://www.gnu.org/licenses/>.
"""

import threading
from ipaddress import ip_address
from random import randrange
import zmq


class Publisher(threading.Thread):
    """Network Bitcoin simulator thread (ZMQ)."""

    def __init__(self):
        """Constructor.
        context - context zmq
        socket - socket p2p
        ip - ip address
        """
        threading.Thread.__init__(self)
        self.context = zmq.Context()
        self.socket = self.context.socket(zmq.PUB)
        self.ip = ip_address(randrange(100))

    def run(self):
        """Run thread."""
        self.socket.bind("tcp://*:4444")

    def broadcast(self, message):
        """Broadcast message.
        message - text message
        """
        message = bytes(message)
        self.socket.send(message)


class Subscriber(threading.Thread):
    """Network Bitcoin simulator thread limited by 120 conections."""

    def __init__(self):
        """Constructor.
        context - context zmq
        socket - socket p2p
        ip - ip address
        """
        threading.Thread.__init__(self)
        self.context = zmq.Context()
        self.socket = self.context.socket(zmq.SUB)
        self.ip = ip_address(randrange(100))

    def run(self):
        """Run thread,"""
        self.socket.connect("tcp://localhost:4444")

    def proxy(self):
        self.ip = ip_address(randrange(100))
